﻿using System;
using System.Net;
using System.Runtime.InteropServices;
using System.Text;

namespace IDesktop.Core {
    public class Downloader {
        [DllImport("wininet.dll")]
        private extern static bool InternetGetConnectedState(out int connectionDescription, int reservedValue);

        public static string Download(string url) {
            string content = string.Empty;
            byte[] buffer;
            int connectionDescription = 0;
            if (InternetGetConnectedState(out connectionDescription, 0)) {
                try {
                    using (WebClient client = new WebClient()) {
                        buffer = client.DownloadData(url);
                    }
                }
                catch (WebException e) {
                    throw new Exception(e.Message);
                }
                if (content != null) {
                    content = Encoding.UTF8.GetString(buffer);
                }
                else {
                    throw new Exception("无法获取天气信息，请检查网络连接或者稍后再试！");
                }
            }
            return content;
        }
    }
}